package com.mycompany.crm.controller;

import com.google.code.kaptcha.Producer;
import com.mycompany.crm.utils.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/code")
public class CaptchaController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Resource
    private Producer captchaProducer;


    @GetMapping("/get_captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String captchaText = captchaProducer.createText();

        String key = getCaptchaKey(request);

        //10分钟过期
        redisTemplate.opsForValue().set(key,captchaText,10,TimeUnit.MINUTES);

        BufferedImage bufferedImage = captchaProducer.createImage(captchaText);

        ServletOutputStream outputStream = null;

        try {
            outputStream = response.getOutputStream();
            ImageIO.write(bufferedImage,"jpg",outputStream);
            outputStream.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            assert outputStream != null;
            outputStream.close();
        }
    }

    public static String getCaptchaKey(HttpServletRequest request){
        String ip = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        return "user-service:captcha:"+CommonUtil.MD5(ip+userAgent);
    }
}
